package com.shy.wonderfuleffect.service

import android.animation.AnimatorSet
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.graphics.PixelFormat
import android.os.Build
import android.os.IBinder
import android.view.Gravity
import android.view.LayoutInflater
import android.view.WindowManager
import android.view.animation.AnticipateInterpolator
import androidx.core.app.NotificationCompat
import com.shy.wonderfuleffect.App
import com.shy.wonderfuleffect.R
import com.shy.wonderfuleffect.activity.MainActivity
import com.shy.wonderfuleffect.databinding.WindowFloatBinding
import com.shy.wonderfuleffect.tool.CommonTools.Companion.dp
import com.shy.wonderfuleffect.tool.CommonTools.Companion.loggingV

class WonderfulService : Service() {
    lateinit var binding: WindowFloatBinding

    @SuppressLint("RemoteViewLayout")
    override fun onCreate() {
        "onCreate".loggingV(this::class.simpleName.toString())
        val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel("WonderfulService",
                "WonderfulService",
                NotificationManager.IMPORTANCE_DEFAULT)
            manager.createNotificationChannel(channel)
        }
        val pendingIntent = PendingIntent.getActivity(this,
            0,
            Intent(this, MainActivity::class.java),
            PendingIntent.FLAG_IMMUTABLE)
        val notification = NotificationCompat.Builder(this, "WonderfulService")
            .setContentTitle("Wonderful Effect")
            .setContentText("Some wonderful effect.")
            .setSmallIcon(R.drawable.ic_baseline_face_retouching_natural_24)
            .setLargeIcon(BitmapFactory.decodeResource(resources,
                R.drawable.ic_baseline_face_retouching_natural_96))
            .setContentIntent(pendingIntent)
//            .setContent(RemoteViews(packageName, R.layout.notification_float).apply {
//                setOnClickPendingIntent(R.id.start_service_btn)
//            })
            .build()
        startForeground(1, notification)
        super.onCreate()
    }

    override fun onBind(intent: Intent): IBinder {
        "onBind".loggingV(this::class.simpleName.toString())
        TODO("Return the communication channel to the service.")
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        "onStartCommand".loggingV(this::class.simpleName.toString())
        addWindow()
        intent?.getStringExtra("cmd")?.let {
            when (it) {
                "big" -> showResizeAnimator(300.dp(this).toInt(), 100.dp(this).toInt())
                "small" -> showResizeAnimator(200.dp(this).toInt(), 30.dp(this).toInt())
                "hide" -> showResizeAnimator(30.dp(this).toInt(), 30.dp(this).toInt())
            }
        }
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onDestroy() {
        "onDestroy".loggingV(this::class.simpleName.toString())
        super.onDestroy()
    }


    @SuppressLint("ClickableViewAccessibility")
    private fun addWindow() {
        if (this::binding.isInitialized) {
            return
        }
        App.binding?.let {
            binding = it
            return
        }
        val windowManager = getSystemService(WINDOW_SERVICE) as WindowManager
//        val outMetrics = DisplayMetrics()
//        windowManager.defaultDisplay.getMetrics(outMetrics)
        val layoutParam = WindowManager.LayoutParams()
        layoutParam.apply {
            //显示的位置
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//                type = WindowManager.LayoutParams.TYPE_ACCESSIBILITY_OVERLAY
                type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
                //刘海屏延伸到刘海里面
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                    layoutInDisplayCutoutMode =
                        WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
                }
            } else {
                type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT
            }
            flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
            flags = flags or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
            flags = flags or WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
//            flags = flags or WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
            width = WindowManager.LayoutParams.MATCH_PARENT
            height = WindowManager.LayoutParams.WRAP_CONTENT
            format = PixelFormat.TRANSLUCENT
            gravity = Gravity.TOP or Gravity.CENTER_HORIZONTAL
        }
        binding = WindowFloatBinding.inflate(LayoutInflater.from(this), null, false)
//        binding.root.setOnTouchListener(FloatWindowTouchListener(layoutParam, windowManager))
        windowManager.addView(binding.root, layoutParam)
        App.binding = binding
    }

    private fun showResizeAnimator(w: Int, h: Int, duration: Long = 300) {
        val rw = binding.cvCard.layoutParams.width
        val rh = binding.cvCard.layoutParams.height
        val widthAnimator = ValueAnimator.ofInt(rw, w).apply {
            this.duration = duration
//            repeatCount = 1
            interpolator = AnticipateInterpolator()
            addUpdateListener { it ->
                (it.animatedValue as Int).let {
                    binding.cvCard.layoutParams = binding.cvCard.layoutParams.apply {
                        width = it
                    }
                }
            }
        }
        val heightAnimator = ValueAnimator.ofInt(rh, h).apply {
            this.duration = duration
//            repeatCount = 1
            interpolator = AnticipateInterpolator()
            addUpdateListener { it ->
                (it.animatedValue as Int).let {
                    binding.cvCard.layoutParams = binding.cvCard.layoutParams.apply {
                        height = it
                    }
                }
            }
        }
        AnimatorSet().apply {
            play(widthAnimator).with(heightAnimator)
            start()
        }
    }
}